package com.dxy.netty.tcppackagesolve;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * @Description "头部包含数据包长度"方式解决粘包拆包问题-netty服务端处理器
 * @Author dangxianyue
 * @Date 2023/1/8 22:09
 */
public class ProtocolNettyServerHandler extends SimpleChannelInboundHandler<ProtocolMessage> {

    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtocolMessage msg) throws Exception {
        String msgStr = new String(msg.getContent(), StandardCharsets.UTF_8);
        System.out.println("==========================");
        String countMsg = String.format("服务端已收到[%s]个数据包", ++this.count);
        System.out.println(countMsg + "，当前数据包：" + msgStr);

        //回送客户端
        byte[] body = countMsg.getBytes(StandardCharsets.UTF_8);
        // 构建一个响应协议包
        ProtocolMessage responseMsg = new ProtocolMessage();
        responseMsg.setLength(body.length);
        responseMsg.setContent(body);
        ctx.writeAndFlush(responseMsg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
